const {dialog,tinymce} = parent.BatchUploadImage;
const editor = tinymce.activeEditor
const uploadHandler = editor.getParam('images_upload_handler', undefined, 'function');
const fileType = editor.getParam('batch_upload_image_type', ['jpg', 'jpeg', 'png', 'gif'], 'array');
// 文件后缀名称小写
const accept = fileType.map(type => `.${type.toLocaleLowerCase()}`).toString();
const uploadButton = document.querySelector('#upload');
const insertButton = document.querySelector('#insert');
const list = document.querySelector('#list');
const tip = document.querySelector('#tip');
const images = [];


const defaultTip = `支持上传${fileType.join('、').toLocaleUpperCase()}格式图片！`
tip.innerHTML = defaultTip

// 添加图片
document.querySelector('#choose').addEventListener('click', () => {
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('multiple', 'multiple');
    input.setAttribute('accept', accept);
    input.onchange = function () {
        checkImage(this.files);
    }
    input.click();
});

// 批量上传
uploadButton.addEventListener('click', function () {
    let length = 0;
    images.forEach(v => {
        if (v.url == '') {
            length++;
            if (v.state == -1) {
                v.state = 0;
            }
        }
    });

    if (length) {
        this.disabled = true;
        uploadQueue();
    }
});

// 取消
document.querySelector('#cancel').addEventListener('click', () => {
    dialog.close();
});

// 清空列表
document.querySelector('#empty').addEventListener('click', () => {
    document.querySelector('#list').innerHTML = '';
    images.length = 0;
});

// 全部插入
document.querySelector('#insert').addEventListener('click', () => {
    if (images.filter(v => v.state != '2').length > 0) {
        bulkUpload()
        return
    }
    insertButton.disabled = true
    // console.log(editor)
    if (images.length) {
        editor.focus();
        let {
            width
        } = editor.selection.getNode().getBoundingClientRect()
        // console.log(width, editor)

        editor.undoManager.transact(async () => {
            for (const src of images) {
                const i = images.indexOf(src);
                let img = editor.dom.create('img', {
                    src: src.url
                })
                // console.log(img, src.url)
                let {w, h} = await getImageInfo(img)
                let relWidth = w > width ? width : w
                if (i == images.length - 1) {
                    editor.dom.setAttribs(img, {
                        'data-mce-id': '__mcenew',
                        style: `width: ${relWidth}px`,
                        width: relWidth
                    });
                    editor.focus();
                    editor.selection.setContent(img.outerHTML);
                    const insertedElm = editor.dom.select('*[data-mce-id="__mcenew"]')[0];
                    editor.dom.setAttrib(insertedElm, 'data-mce-id', null);
                    editor.selection.select(insertedElm);
                } else {
                    editor.dom.setAttribs(img, {
                        style: `width: ${relWidth}px`,
                        width: relWidth
                    });
                    editor.focus();
                    editor.insertContent(img.outerHTML);
                }
            }
            insertButton.disabled = false
            dialog.close();
        })
    }
});

/**
 * 拖拽上传
 * https://developer.mozilla.org/zh-CN/docs/Web/API/Document/drop_event
 */
document.addEventListener('dragover', e => e.preventDefault());
document.querySelector('#main').addEventListener('drop', function (e) {
    e.preventDefault();
    checkImage(e.dataTransfer.files);
});

// 删除
list.addEventListener('click', ({target}) => {
    if (target.classList.contains('remove')) {
        let index = Array.from(list.querySelectorAll('.remove')).indexOf(target);
        list.removeChild(target.parentElement);
        delete images.splice(index, 1);
    }
});

// 获取图片长宽
function getImageInfo(img) {
    return new Promise(resolve => {
        if (img.complete) {
            // 如果图片被缓存，则直接返回缓存数据
            resolve({w: img.width, h: img.height});
        } else {
            img.onload = function () {
                resolve({w: img.width, h: img.height});
            }

            img.onerror = function () {
                resolve({w: -1, h: -1});
            }
        }
    })
}

// 获取文件扩展名
function ext(filename) {
    return filename.split('.').pop().toLocaleLowerCase();
}

// 检查图片格式
function checkImage(files) {
    if (files.length) {
        const _files = Array.from(files).filter(file => fileType.includes(ext(file.name)));
        let items = _files.map(file => {
            let blobUrl = window.URL.createObjectURL(file);
            images.push({file: file, blobUrl: blobUrl, url: '', state: 0});
            return `<li class="item" data-state="0"><img class="image" src="${blobUrl}" alt=""><div class="name" title="${file.name}">${file.name}</div><span class="remove"></span></li>`;
        });
        list.innerHTML += items.join('');
        bulkUpload()
    }
}

// 图片上传队列
function uploadQueue() {
    tip.innerHTML = images.filter(v => v.state != '2').length > 0 ? `请继续上传或删除还未上传成功的图片！` : defaultTip

    let index = images.findIndex(v => v.state == 0);
    if (index == -1) {
        uploadButton.disabled = false;
        return;
    }

    let item = list.querySelectorAll('li')[index];
    item.dataset.state = '1'; // 上传中

    const img = images[index];

    fileToBase64(img.file, (res) => {
        let data = {
            file: img.file,
            base64: () => res,
            blob: () => base64ToBlob(res)
        };
        uploadHandler(data, function (url) {
            img.url = url;
            img.state = 2;
            item.dataset.state = '2'; // 上传成功
            item.removeAttribute('data-tip')
            uploadQueue();
        }, function (err) {
            img.state = -1;
            item.dataset.state = '-1'; // 上传失败
            item.dataset.tip = err || '上传失败'; // 上传失败
            uploadQueue();
        });
    })
}

/**
 批量上传
 */
function bulkUpload() {
    let length = 0;
    images.forEach(v => {
        if (v.url == '') {
            length++;
            if (v.state == -1) {
                v.state = 0;
            }
        }
    });

    if (length) {
        uploadButton.disabled = true;
        uploadQueue();
    }
}

/**
 * 获取文件的Base64
 * @param file      {File}      文件
 * @param callback  {Function}  回调函数，参数为获取到的base64
 */
function fileToBase64(file, callback) {
    const fileReader = new FileReader()
    fileReader.readAsDataURL(file)
    fileReader.onload = function () {
        callback(this.result.split(',')[1])
    }
}

/**
 * base64转blob
 * @param code
 * @returns {Blob}
 */
function base64ToBlob(code) {
    let parts = code.split(';base64,');
    let rawLength, contentType, raw;
    if (parts.length > 1) {
        contentType = parts[0].split(':')[1];
        raw = window.atob(parts[1]);
        rawLength = raw.length;
    } else {
        raw = window.atob(parts[0]);
        rawLength = raw.length;
    }

    let uInt8Array = new Uint8Array(rawLength);
    for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], {
        type: contentType
    });
}